<template>
  <el-card shadow="hover">
    {{movieSearch}}
    <!--条件查询 -->
    <el-form :inline="true" :model="movieSearch" class="demo-form-inline" size="medium">
      <el-form-item >
        <el-input v-model="movieSearch.title" placeholder="电影标题" />
      </el-form-item>
      <el-form-item label="电影分类">
        <el-select v-model="movieSearch.category_id" placeholder="选择分类">
          <el-option label="所有分类" value="0"></el-option>
          <el-option :label="c.category_name" :value="c.id" v-for="c in categories"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" icon="el-icon-search" plain>查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="add" icon="el-icon-plus" plain>添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="handleDelete" icon="el-icon-remove" plain>批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="movies"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="电影ID"
          prop="id"
          align="center"
          width="180" />
      <el-table-column
          label="标题"
          prop="title"
          align="center" />
      <el-table-column
          label="导演"
          prop="director"
          align="center" />
      <el-table-column
          label="编剧"
          prop="screenwriter"
          align="center" />
      <el-table-column
          label="主演"
          prop="lead_actors"
          align="center" />
      <el-table-column
          label="上映年份"
          prop="release_year"
          align="center" />
      <el-table-column
          label="片长(分钟)"
          prop="runtime"
          align="center" />
      <el-table-column
          label="评分"
          prop="rating"
          align="center" />
      <el-table-column
          label="票房(万元)"
          prop="box_office"
          align="center" />
      <el-table-column
          label="分类"
          prop="category_name"
          align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页导航-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!--编辑电影对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{movie}}
      <el-form :model="movie" :rules="rules" ref="ruleForm">
        <el-form-item label="电影标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="movie.title" autocomplete="off" placeholder="请输入电影标题"></el-input>
        </el-form-item>
        <el-form-item label="导演" :label-width="formLabelWidth" prop="director">
          <el-input v-model="movie.director" autocomplete="off" placeholder="请输入导演"></el-input>
        </el-form-item>
        <el-form-item label="编剧" :label-width="formLabelWidth" prop="screenwriter">
          <el-input v-model="movie.screenwriter" autocomplete="off" placeholder="请输入编剧"></el-input>
        </el-form-item>
        <el-form-item label="主演" :label-width="formLabelWidth" prop="lead_actors">
          <el-input v-model="movie.lead_actors" autocomplete="off" placeholder="请输入主演"></el-input>
        </el-form-item>
        <el-form-item label="上映年份" :label-width="formLabelWidth" prop="release_year">
          <el-input v-model.number="movie.release_year" autocomplete="off" placeholder="请输入上映年份"></el-input>
        </el-form-item>
        <el-form-item label="片长(分钟)" :label-width="formLabelWidth" prop="runtime">
          <el-input v-model.number="movie.runtime" autocomplete="off" placeholder="请输入片长"></el-input>
        </el-form-item>
        <el-form-item label="评分" :label-width="formLabelWidth" prop="rating">
          <el-input v-model.number="movie.rating" autocomplete="off" placeholder="请输入评分"></el-input>
        </el-form-item>
        <el-form-item label="票房(万元)" :label-width="formLabelWidth" prop="box_office">
          <el-input v-model.number="movie.box_office" autocomplete="off" placeholder="请输入票房"></el-input>
        </el-form-item>
        <el-form-item label="电影分类" :label-width="formLabelWidth" prop="category_id">
          <el-select v-model="movie.category_id" placeholder="请选择分类">
            <el-option :label="c.category_name" :value="c.id" v-for="c in categories"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电影简介" :label-width="formLabelWidth" prop="description">
          <el-input v-model="movie.description" autocomplete="off" placeholder="请输入电影简介" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  data() {
    var checkYear = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('上映年份不能为空'));
      } else if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else if (value < 1800 || value > new Date().getFullYear()) {
        callback(new Error('上映年份必须在1800 - ' + new Date().getFullYear() + '之间'));
      } else {
        callback();
      }
    };
    var checkRating = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('评分不能为空'));
      } else if (isNaN(value)) {
        callback(new Error('请输入数字值'));
      } else if (value < 0 || value > 10) {
        callback(new Error('评分必须在0 - 10之间'));
      } else {
        callback();
      }
    };
    return {
      movies: [],
      page: 1,       // 当前页
      pageSize: 5,   // 每页大小
      total: 100,    // 总记录数
      title: '添加电影',    // 对话框标题
      movieSearch: {},  // 代表对电影进行条件查询,此对象封装的是查询的电影
      categories: [],         // 所有分类列表
      dialogFormVisible: false,  // 对话框是否可见，true：可见 false：隐藏
      movie: {},        // 添加或修改的电影对象
      formLabelWidth: '100px', // 表单项的标签宽度
      multipleSelection: [],  // 多选框选中的记录列表
      movieIds: [],                // 存放要删除的电影编号
      // 定义验证规则
      rules: {
        title: [
          { required: true, message: '请输入电影标题', trigger: 'blur' }
        ],
        director: [
          { required: true, message: '请输入导演', trigger: 'blur' }
        ],
        release_year: [
          { validator: checkYear, trigger: 'blur' }
        ],
        rating: [
          { validator: checkRating, trigger: 'blur' }
        ],
        category_id: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    // 1. 查询所有电影列表
    // this.getMovies()
    // 2. 分页查询电影信息
    // this.findByPage()
    this.search();
    // 3. 查询所有分类列表
    this.findCategories();
  },

  methods: {    // 定义普通方法
    // 处理多选事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    // 最后，提交表单，保存电影信息（添加或修改）
    save() {
      // 第一步：进行表单校验
      this.$refs['ruleForm'].validate(valid => {   // valid的值为true表示验证通过，为false表示验证失败（有一个表单元素未通过就是false）
        if (valid) {
          // 不管添加还是修改，提交到后台的就是url地址不同，数据都是movie对象
          let url = '/movie?cmd=add';
          // 如何区分添加还是修改？根据movie对象中的id属性，如果id为null，则添加，否则修改
          if (this.movie.id) { // 修改操作
            url = '/movie?cmd=update';
          }
          // 最后，提交到后台
          this.$axios.post(url, this.movie).then(resp => {
            if (resp.data.code == '200') {
              // 添加成功
              // 1. 关闭对话框
              this.dialogFormVisible = false;
              // 2. 刷新列表
              this.search();
              // 3. 提示信息
              this.$message({
                type: 'success',
                message: resp.data.message
              });
            } else {
              // 添加失败
              this.$message.error(resp.data.message);
            }
          });
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    search() {
      this.$axios.post(`/movie?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,
          this.movieSearch).then(res => {
        this.movies = res.data.rows;
        this.total = res.data.total;
        console.log(res);
      });
    },
    getMovies() {
      this.$axios.get('/movie?cmd=list').then(res => {
        this.movies = res.data;
      });
    },
    // 分页查询
    findByPage() {
      this.$axios.get(`/movie?cmd=findByPage&page=${this.page}&pageSize=${this.pageSize}`).then(res => {
        console.log(res);
        this.movies = res.data.rows;
        this.total = res.data.total;
      });
    },
    // 查询所有分类:
    findCategories() {
      this.$axios.get('/movie_category').then(res => {
        this.categories = res.data;
      });
    },
    // 添加电影
    add() {
      // 1. 设置标题
      this.title = "添加电影";
      // 2. 重置数据
      this.movie = {};
      // 3. 显示对话框
      this.dialogFormVisible = true;
    },
    // 每页大小pageSize改变时触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      // this.findByPage()
      this.search();
    },
    // 当前页page改变时触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      // this.findByPage()
      this.search();
    },
    // 编辑电影
    handleEdit(index, row) {
      console.log(index, row);
      // 1. 为movie对象赋值
      this.movie = row;
      // 2. 为title赋值
      this.title = "修改电影";
      // 3. 显示对话框
      this.dialogFormVisible = true;
    },
    // 删除电影
    handleDelete(index, row) {
      // 第一步：组织我们要删除的电影编号到数组 movieIds中
      if (row) {  // 点击了单个删除按钮
        this.movieIds = [row.id];
      } else {    // 点击了批量删除按钮
        this.movieIds = this.multipleSelection.map(m => m.id);
      }
      // 第二步：访问后台根据电影编号数组来删除电影
      this.$confirm(`你是否真的要删除电影ID为${this.movieIds}的电影?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // 确定按钮点击事件
        this.$axios.get(`/movie?cmd=delete&movieIds=${this.movieIds}`).then(res => {
          if (res.data.code == '200') {
            // 删除成功
            // 1. 提示信息
            this.$message({
              type: 'success',
              message: res.data.message
            });
            // 2. 刷新列表
            this.search();
          } else {
            // 删除失败
            this.$message.error(res.data.message);
          }
        });
      }).catch(() => {  // 取消按钮点击事件
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
};
</script>

<style>
.el-card {
  width: 90%;
  margin: 20px auto;
}
.el-pagination {
  text-align: right;
  margin-top: 20px;
}
</style>